<template>
<!-- 平安清分鉴权 --  ｜ 小额鉴权（企业性质） ｜ 银联鉴权 (个人性质)-->
<div>
  <!-- 核对银行卡信息 bankInfo -->
  <el-dialog v-if="!authVisible" title="银行卡信息核对" :visible.sync="dialogVisible" :show-close="false" :close-on-click-modal="closeModal" :close-on-press-escape="closeEscape" :before-close="close" class="dialog-container" width="750px">
    <div class="auth-form-wrapper">
      <el-form ref="bankForm" label-width="80px" :label-position="'right'" size="mini">
        <el-row>
          <el-col :span="12">
            <el-form-item label="开户银行">
              <el-input v-model="bankForm.bankName" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="开户支行">
              <el-input v-model="bankForm.branchBankName" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="银行卡号">
              <el-input v-model="bankForm.accountNo" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="证件类型">
              <el-input v-model="bankForm.certificateTypeName" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="证件号码">
              <el-input v-model="bankForm.certificateNo" :disabled="true"></el-input>
            </el-form-item>
            <el-form-item label="手机号码">
              <el-input v-model="bankForm.reservePhone" :disabled="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="auth-notice-wrapper">
      <div class="notice-title"><i class="el-icon-bell">温馨提示：</i></div>
      <div class="notice-item">
        今日剩余鉴权次数：<span class="notice-item-num">{{ bankForm.verifyNum  || 0 }}</span> 次
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button size="mini" @click="exitAuth()">取消</el-button>
      <el-button size="mini" type="primary" @click="gotoAuth()" :loading="authLoading" :disabled="isShowAuthBtn">{{authBtnName}}</el-button>
    </div>
  </el-dialog>
  <!-- 鉴权 auth -->
  <el-dialog v-if="authVisible" :title="flag ==='small' ? '小额鉴权' : '银联鉴权'" :visible.sync="authVisible" :show-close="false" :close-on-click-modal="closeModal" :close-on-press-escape="closeEscape" :before-close="close">
    <!-- 小额鉴权（企业性质）smallAmount -->
    <div class="small-amount" v-if="flag==='small'">
      <p>{{`平安银行已经向您 ${bankForm.bankName}`}} {{formatBankNumber(bankForm.accountNo)}} {{`的银行卡内打入一笔小于1元的金额，请输入正确的鉴权金额`}}</p>
      <el-form :model="authForm" :rules="rulesMoney" ref="authForm" label-width="100px">
        <el-form-item label="金额"  prop="message">
          <el-input v-model="authForm.message" autocomplete="off" placeholder="建议输入0.01元" style="width:50%" maxlength="20"></el-input>
        </el-form-item>
        <el-form-item label="指令码"  prop="smsCode">
          <el-input v-model="authForm.smsCode" autocomplete="off" placeholder="请输入指令码" style="width:50%" maxlength="20"></el-input>
        </el-form-item>
      </el-form>
    </div>
    <!-- 银联鉴权 (个人性质) unionPay -->
    <div class="union-pay" v-else>
      <p>{{`平安银行已经向您${bankForm.bankName} ${formatPhone(bankForm.reservePhone)} 的手机号发送短信验证码，请输入正确的鉴权验证码`}}</p>
      <el-form :model="authForm" :rules="rulesCode" ref="authForm" label-width="100px">
        <el-form-item label="验证码" prop="message">
          <el-input v-model="authForm.message" autocomplete="off" placeholder="请输入验证码" style="width:50%" maxlength="20"></el-input>
        </el-form-item>
      </el-form>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button size="mini" type="primary" :loading="submitLoading" @click="submit">提 交</el-button>
    </div>
  </el-dialog>
</div>
</template>

<script>
import dialog from '@mix/dialog'
import { triggerAuthApi, authenticationApi, smallAmountTransferCheckApi } from '@/api/finance'
import moment from 'moment'

export default {
  mixins: [dialog],
  props: {
    bankForm:{
      type: Object,
      default: () => ({})
    }
  },
  data() {
    var validateMoney = (rule, value, callback) => {
        if (!value) {
          callback(new Error('请输入金额'));
        } else {
          if(value >= 1){
            callback(new Error('请输入小于1元的金额'))
          }
          callback();
        }
      };
    return {
      authVisible: false,
      authLoading: false,
      isShowAuthBtn: true,
      authBtnName:'去鉴权',
      authForm:{},
      flag: 'small',      //small (小额) ｜ union （银联）
      rulesMoney:{
        message:[
          { required: true, message: '请输入金额', trigger: 'blur' },
          { pattern: /^\d+(\.\d{0,2})?$/, message: '请输入正确金额,且最多保留两位小数', trigger: 'blur' },
          { validator: validateMoney, trigger: 'blur' },
        ],
        smsCode: [
          { required: true, message: '请输入指令码', trigger: 'blur'}
        ]
      },
      rulesCode:{
        message:[
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { pattern: /^\d+$/, message: '请输入正确验格式证码', trigger: 'blur' },
        ]
      },
      submitLoading: false
    }
  },
  created() {
    this.initPage()
  },
  computed:{
    waitTime(){
      let time = moment.duration(this.bankForm.waitSeconds,'seconds') 
      let moment_time = moment.duration(time, 'milliseconds');
      let hours = Math.floor(moment_time.asHours());
      let mins = Math.floor(moment_time.asMinutes()) - hours * 60;
      return ` ${hours} 小时 ${mins} 分`
    }
  },
  methods: {
    /**
     * 
     * peaceAuthPage
     * GOTO_AUTH 显示去鉴权按钮
     * GOTO_AUTH_TIME 展示 去鉴权页面页面按钮提示：距离上次鉴权时间太短，需要等待23:30:30（剩余时间）
     * AUTH_PROCESSING  页面显示处理中
     * AMOUNT_ENTRY  金额输入页面(对公,小额鉴权)
     * AUTH_CODE_ENTRY   验证码输入页面(对私，银联鉴权)
     */
    initPage(){
      switch(this.bankForm.peaceAuthPage){
        case 'GOTO_AUTH': 
          this.isShowAuthBtn = false
          break
        case 'GOTO_AUTH_TIME':
          this.isShowAuthBtn = false
          break
        case 'AUTH_PROCESSING':
          this.authLoading = true
          this.authBtnName = '处理中，请稍后...'
          break
        case 'AMOUNT_ENTRY':
          this.flag = 'small'
          this.authVisible = true
          break
        case 'AUTH_CODE_ENTRY':
          this.flag = 'union'
          this.authVisible = true
          break
        default:
          break      
      }
    },
    //触发鉴权，返回200, 跳转鉴权
    async triggerAuth(){
      this.authLoading = true
      try{
        const { code } = await triggerAuthApi()
        if(code !== 200){
          this.authLoading = false
          return
        } 
        if(this.flag === 'small'){
          this.smallAmountTransferCheck()
        }else{
          this.authVisible = true
          this.authLoading = false
        }
      }catch(e){
        console.log(e)
        this.authLoading = false
      }
    },
    // 检测银行打款成功与否,对方账户会收到打款金额，巴拉巴拉这样。。。
    // 小额鉴权需要触发鉴权后，等银行打款成功，方可输入金额鉴权，类似发验证码
    // SUCCESS(0, "转账成功"), FAILED(1, "转账失败"), BE_CONFIRMED(2, "处理中"), NOT_START(3, "未开始");
    // 返回{0:"转账成功"}
    async smallAmountTransferCheck(){
      try{
        const { code,result = {} } = await smallAmountTransferCheckApi()
        if(code !== 200 ){
          this.authLoading = false
          return
        } 
        switch(Object.keys(result)[0]){
          case '0':
            this.authLoading = false
            this.authVisible = true
            this.$message.success('请输入鉴权金额')
            break
          case '1':
            this.authLoading = false
            this.authVisible = false
            this.$message.success('转账失败请重试')
            break
          case '2':
          case '3':
            this.authLoading = true
            this.authVisible = false
            setTimeout(()=>{this.smallAmountTransferCheck()},3000)
            break
          default:
            this.authLoading = true
            this.authVisible = false
            break        
        }
      }catch(e){
        console.log(e)
      }
    },
    //银行卡脱敏
    formatBankNumber(val) {
      if(!val) return ''
      return `${val.slice(0, 3)} ${val.slice(3, 7)} **** ${val.slice(11, val.length)}`
    },
    //手机号脱敏
    formatPhone(val) {
      if(!val) return ''
      return `${val.slice(0,3)} **** ${val.slice(7,val.length)}`
    },
    // 去鉴权  小额鉴权（企业性质） ｜ 银联鉴权 (个人性质)
    // cardType 1对公  2对私
    gotoAuth(){
      if(this.bankForm.peaceAuthPage === 'GOTO_AUTH_TIME'){
        this.$alert(`距离上次鉴权时间太短，需要等待${this.waitTime}`, '提示', {
          confirmButtonText: '确定',
          type: 'warning',
          callback: () => {}
        });
        return
      }
      if(!this.bankForm.cardType){
        this.$message.error('信息异常，请联系相关业务人员')
        return 
      } 
      if(this.bankForm.cardType === 1){
        this.flag = 'small'
        this.triggerAuth()
      }else if(this.bankForm.cardType === 2){
        this.flag = 'union'
        this.triggerAuth()
      }
    },
    //提交鉴权
    submit() {
      this.$refs['authForm'].validate(async valid=>{
        if(valid){
          this.submitLoading = true
          const { code } = await authenticationApi(this.authForm)
          if(code === 200){
            this.$message.success('鉴权成功');
            this.close()
            this.submitLoading = false
          }else{
            this.submitLoading = false
          }
        }
      })
    },
    exitAuth(){
      this.$emit('exit')
    }
    // 获取账号信息，主要是拿等待时间（暂定）
    // async getAccountInfo(){
      
    // }
  }
}
</script>

<style lang="less" scoped>
.auth-notice-wrapper{
  padding: 0 10px;
  color: #A6A6A6;
  font-size: 16px;
  .notice-title{
    margin-bottom: 6px;
  }
  .notice-item{
    font-size: 14px;
    .notice-item-num{
      color:#67C23A
    }
  }
}
</style>
